package cz.cvut.fit.mi_paa.knapsack.strategy;

import cz.cvut.fit.mi_paa.abs.Context;
import cz.cvut.fit.mi_paa.knapsack.KnapsackContext;
import cz.cvut.fit.mi_paa.knapsack.KnapsackInstance;
import cz.cvut.fit.mi_paa.knapsack.Item;

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: milos
 * Date: 1.10.12
 * Time: 11:21
 * To change this template use File | Settings | File Templates.
 */
public class PriceWeightHeuristicKnapsackStrategy extends KnapsackStrategy {
    private int solWeight;
    private int solPrice;
    private List<Item> resultList;
    public PriceWeightHeuristicKnapsackStrategy(Context context) {
        super(context);
        resultList = new ArrayList<Item>();
    }

    @Override
    public void solve() throws IOException {
        context.getSw().start();
        Item[] items = instance.getItems();
        Arrays.sort(items, new Comparator<Item>() {
            @Override
            public int compare(Item o1, Item o2) {
                if (o2.getRatio() > o1.getRatio()) {
                    return 1;
                } else if (o2.getRatio() == o1.getRatio()) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        for (Item item : items) {
            if(item.getWeight()>instance.getCapacity()) continue;
            if((solWeight+item.getWeight())<=instance.getCapacity()) {
                solPrice+=item.getPrice();
                solWeight+=item.getWeight();
                resultList.add(item);
            }
        }
        context.getSw().stop();
    }

    @Override
    public void writeResult() throws IOException {
        Collections.sort(resultList, new Comparator<Item>() {
            @Override
            public int compare(Item o1, Item o2) {
                if (o1.getIndex() > o2.getIndex()) {
                    return 1;
                } else if (o1.getIndex() == o2.getIndex()) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        FileWriter resultWriter = context.getResultWriter();
        resultWriter.write(instance.getId() + " ");
        resultWriter.write(context.getSw().getTimeMillis() + " ");
        resultWriter.write(instance.getItemNumber() + " ");
        resultWriter.write(solPrice+ "  ");
        int[] arr = new int[instance.getItemNumber()];
        for (Item item : resultList) {
            arr[item.getIndex()] = 1;
        }
        for (int i = 0; i<arr.length;i++) {
            if(i!=(arr.length-1))
                resultWriter.write(arr[i]+" ");
            else
                resultWriter.write(arr[i]+"\n");
        }

    }
}
